#include "typedefs.h"
#include "_reg54.h"
#include "reg.h"
#include "serial.h"
//#include "printf.h"

extern irq_flag_global;

#ifdef SERIAL

#if (defined(W78E516) && defined(BOOTLOADER))||defined(TW2835_OSD_ONLY)
#define BUF_MAX 	128
#else
#define BUF_MAX 	4
#endif

//#ifndef BOOTLOADER
//xdata char	RS_buf[BUF_MAX] = {0x00,0x00,0x00,0x00};
//#else
idata char	RS_buf[BUF_MAX];
//#endif

data char   RS_in, RS_out;
bit	    RS_Xbusy=0;			// bit RS_Xbusy=0;


void serial_init(void)
{

	/* TH1 Value: SMOD=1, */
	//0xffh is for 115200bps@24MHz crystal,this is used for EVB;
	//0xfah is for 9600bps@11.0592MHz crystal,for ICE use only;
	//0xeah is for 9600bps@40MHz, this is used for Jushi releaseb board.
	TH1 = 0xea;
	// Enable serial reception		
	SCON = 0x50;		// 0101 0000 mode 1 - 8 bit UART				
									

	TMOD = 0x21;		// 0010 0001 timer 0 - 16 bit 
					// timer 1 - baud rate generator				

	TCON = 0x55;		// 0101 0001 timer 0,1 run						
					// int 0,  edge triggered						
					// int 1,  edge triggered						
					// TF1 TR1 TF0 TR0	EI1 IT1 EI0 IT0			
	TR1=1;

	PCON = PCON | 0x80;		// 1000 0000 SMOD(double baud rate bit) = 1		
	PCON = PCON & (~0x40);	// 1000 0000 SMOD(double baud rate bit) = 1		

	PS	 = 1;				// 0000 0000 interrupt priority					
							// -  PS1 PT2 PS0 PT1 PX1 PT0 PX0	 		         
	ES	 = 1;	    		// 1001 0010 interrupt enable:Serial,TM0		
  							// EA - ET2 ES ET1 EX1 ET0 EX0		
			
	TI=1;

	RS_in =0;
	RS_out =0;
	RS_Xbusy=0;
}

//INTERRUPT(4, serial_int)
void serial_int(void) interrupt 4		// register bank 1
{
	if( RI ) {					//--- Receive interrupt ----
		RI = 0;
		RS_buf[RS_in++] = SBUF;
		if( RS_in>=BUF_MAX ) RS_in = 0;
		//irq_flag_global = 1;
	}

	if( TI ) {					//--- Transmit interrupt ----
		TI = 0;
		TI = 0;
		TI = 0;
		RS_Xbusy=0;
	}
}

//=============================================================================
//		Serial RX Check 												   
//=============================================================================
U8 RS_ready(void)
{
	if( RS_in == RS_out ) return 0;
	else return 1;
}
//=============================================================================
//		Serial RX														   
//=============================================================================
unsigned char RS_rx(void)
{
	unsigned char	ret;
		
	ES = 0;
	ret = RS_buf[RS_out];
	RS_out++;
	if(RS_out >= BUF_MAX) 
		RS_out = 0;
	ES = 1;

	return ret;
}
//=============================================================================
//		Serial TX														   
//=============================================================================
void RS_tx(U8 tx_buf)
{
	while(RS_Xbusy);
	SBUF = tx_buf;
	RS_Xbusy=1;
}

#endif	// SERIAL



